package org.thinkinbunny.financial.activity;

import java.util.ArrayList;
import java.util.Calendar;

import org.thinkinbunny.financial.R;
import org.thinkinbunny.financial.billentity.BillEntiry;
import org.thinkinbunny.financial.data.DbHelper;
import org.thinkinbunny.financial.util.DLog;
import org.thinkinbunny.financial.util.ShowTools;
import org.thinkinbunny.financial.view.InputDialog;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TimePicker;

public class NewBillActivity extends MyActivity implements OnClickListener {
	View newBillViewLeft;
	View newBillViewRight;
	Spinner spinner_type;
	Spinner spinner_project;
	Spinner spinner_account;
	RelativeLayout saveBtn, CancelBTN;
	private final static int DATE_DIALOG = 0;
	private final static int TIME_DIALOG = 1;
	private Calendar c = null;
	BillEntiry billEntiry, entirtyBundle;
	ArrayAdapter adaptertypesource;
	ArrayAdapter adaptertypeaccount;
	ArrayAdapter adaptertypeproject;
	private final ArrayList typesource = new ArrayList();

	private final ArrayList accountsource = new ArrayList();//
	private final ArrayList projectsource = new ArrayList();//
	EditText bill_input_balance;
	Button DateInput, TimeInput, spinner_type_ADD, spinner_account_ADD,
	spinner_project_ADD;
	EditText storename;
	DbHelper dbHelper;// = new DbHelper(this, DbHelper.DbName);
	SQLiteDatabase db;// = dbHelper.getReadableDatabase();
	Cursor cursor;// = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		setContentView(R.layout.activity_newbill);
		try {
			entirtyBundle = (BillEntiry) getIntent().getBundleExtra(
					"entirtyBundle").getSerializable("entirty");
		} catch (Exception e) {
			// TODO: handle exception
		}
		billEntiry = new BillEntiry();
		init_UI(entirtyBundle);


		super.onCreate(savedInstanceState);

	}

	@Override
	protected void finalize() throws Throwable {
		// TODO Auto-generated method stub
		cursor.close();
		cursor = null;
		db.close();
		dbHelper.close();

		super.finalize();
	}

	@SuppressWarnings("unchecked")
	void init_spinnerSource() {
		dbHelper = new DbHelper(this, DbHelper.DbName);
		db = dbHelper.getReadableDatabase();
		cursor = null;
		try {

			cursor = db.rawQuery("select type from typeTable", null);
			while (cursor.moveToNext()) {
				typesource.add(cursor.getString(cursor.getColumnIndex("type")));

			}
			cursor.close();
			cursor = db.rawQuery("select account from accountTable", null);
			while (cursor.moveToNext()) {
				accountsource.add(cursor.getString(cursor
						.getColumnIndex("account")));

			}
			cursor.close();
			cursor = db.rawQuery("select project from projectTable", null);
			while (cursor.moveToNext()) {
				projectsource.add(cursor.getString(cursor
						.getColumnIndex("project")));

			}

		} catch (SQLException e) {
			// TODO: handle exception
		} finally {

			cursor.close();

			db.close();
			dbHelper.close();

		}

	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub

		super.onDestroy();
	}

	void init_UI(BillEntiry entirtyBundle) {
		init_spinnerSource();
		spinner_type = (Spinner) findViewById(R.id.spinner_type);
		spinner_account = (Spinner) findViewById(R.id.spinner_account);
		spinner_project = (Spinner) findViewById(R.id.spinner_project);
		bill_input_balance = (EditText) findViewById(R.id.bill_input_balance);
		DateInput = (Button) findViewById(R.id.DateInput);
		TimeInput = (Button) findViewById(R.id.TimeInput);
		storename = (EditText) findViewById(R.id.storename);
		saveBtn = (RelativeLayout) findViewById(R.id.SaveBtn);
		CancelBTN = (RelativeLayout) findViewById(R.id.CancelBTN);
		spinner_type_ADD = (Button) findViewById(R.id.spinner_type_ADD);
		spinner_account_ADD = (Button) findViewById(R.id.spinner_account_ADD);
		spinner_project_ADD = (Button) findViewById(R.id.spinner_project_ADD);



		// spinner_type.setAdapter(adapter)
		saveBtn.setOnClickListener(this);
		CancelBTN.setOnClickListener(this);
		spinner_type_ADD.setOnClickListener(this);
		spinner_account_ADD.setOnClickListener(this);
		spinner_project_ADD.setOnClickListener(this);

		DateInput.setOnClickListener(this);
		TimeInput.setOnClickListener(this);
		adaptertypesource = new ArrayAdapter<ArrayList<String>>(this,
				android.R.layout.simple_spinner_item, typesource);
		adaptertypesource
		.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		adaptertypeaccount = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, accountsource);
		adaptertypeaccount
		.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		adaptertypeproject = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, projectsource);
		adaptertypeproject
		.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		spinner_type.setAdapter(adaptertypesource);
		spinner_account.setAdapter(adaptertypeaccount);
		spinner_project.setAdapter(adaptertypeproject);
		spinner_project.setPrompt(getString(R.string.chooseProject));
		if (entirtyBundle != null) {

			bill_input_balance.setText(entirtyBundle.getBalance() + "");
			spinner_type.setSelection(typesource.indexOf(entirtyBundle
					.getBillType()));
			DateInput.setText(entirtyBundle.getDate());
			TimeInput.setText(entirtyBundle.getTime());
			spinner_account.setSelection(accountsource.indexOf(entirtyBundle
					.getAccountname()));
			storename.setText(entirtyBundle.getStore());
			spinner_project.setSelection(projectsource.indexOf(entirtyBundle
					.getProject()));

		}

	}

	BillEntiry creatEntiry() {
		BillEntiry tempEntiry=new BillEntiry();
		try {
			tempEntiry.setBalance(Float.parseFloat(bill_input_balance.getText()
					.toString()));
			if (entirtyBundle!=null) {
				tempEntiry.set_id(entirtyBundle.get_id());

			}
			tempEntiry.setAccountname(spinner_account.getSelectedItem().toString());
			tempEntiry.setBillType(spinner_type.getSelectedItem().toString());
			tempEntiry.setProject(spinner_project.getSelectedItem().toString());
			tempEntiry.setTime(TimeInput.getText().toString());
			tempEntiry.setDate(DateInput.getText().toString().trim());
			tempEntiry.setStore(storename.getText().toString().trim());
			return tempEntiry;
		} catch (Exception e) {

			return null;
		}




	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub

		switch (v.getId()) {
		case R.id.DateInput:
			onCreateDialog(DATE_DIALOG).show();

			break;
		case R.id.SaveBtn: {
			billEntiry = creatEntiry();
			if (checkBillEntity(billEntiry)) {
				if (entirtyBundle == null) {
					if (DbHelper.insertIntobill(getApplicationContext(),
							billEntiry)) {
						ShowTools.toast(getString(R.string.billsaved));
					}
				} else {
					if (DbHelper.updateIntobill(getApplicationContext(),
							billEntiry)) {
						ShowTools.toast(getString(R.string.billsaved));
					}
				}

			}else {
				ShowTools.toast(getString(R.string.billInfoErr));
			}

			billEntiry=null;

		}

		break;

		case R.id.TimeInput:

			onCreateDialog(TIME_DIALOG).show();
			break;
		case R.id.spinner_type_ADD:
			InputDialog.buildDialogForText(NewBillActivity.this, 1).show();
			break;
		case R.id.spinner_account_ADD:
			InputDialog.buildDialogForText(NewBillActivity.this, 2).show();
			break;
		case R.id.spinner_project_ADD:
			InputDialog.buildDialogForText(NewBillActivity.this, 3).show();
			break;
		case R.id.CancelBTN:
			finish();
			System.exit(0);
			break;

		}

	}

	public boolean checkBillEntity(BillEntiry billEntiry) {

		if (billEntiry==null) {
			return false;
		}
		DLog.i("NewBillActivity", billEntiry.toString());
		try {
			if (Double.valueOf(billEntiry.getBalance()) <= 0
					|| TextUtils.isEmpty(billEntiry.getStore().trim())
					|| TextUtils.isEmpty(billEntiry.getDate().trim())
					|| TextUtils.isEmpty(billEntiry.getTime().trim())) {

				ShowTools.toast(getString(R.string.billInfoErr));
				return false;
			}
		} catch (Exception e) {
			// TODO: handle exception
		}

		return true;

	}

	/**
	 * 创建日期及时间选择对话框
	 */
	@Override
	protected Dialog onCreateDialog(int id) {
		Dialog dialog = null;
		switch (id) {
		case DATE_DIALOG:
			c = Calendar.getInstance();
			dialog = new DatePickerDialog(this,
					new DatePickerDialog.OnDateSetListener() {
				@Override
				public void onDateSet(DatePicker dp, int year,
						int month, int dayOfMonth) {
					String mString,dString;
					if (month<9) {
						mString="0"+(month +1 );
					}else {
						mString=month +1 +"";
					}

					if (dayOfMonth<9) {
						dString="0"+(dayOfMonth +1 );
					}else {
						dString=""+(dayOfMonth +1 );
					}
					DLog.i("xiawei", dp.toString()+""+year+month+dayOfMonth);
					DateInput.setText(year+"-"+mString+"-"+dString);
					//					if (month < 9 && dayOfMonth < 10) {
					//						DateInput.setText(year + "-0" + (month + 1)
					//								+ "-0" + dayOfMonth);
					//						DLog.i("xiawei", year + "-0" + (month + 1)
					//								+ "-0" + dayOfMonth+"(month < 9 && dayOfMonth < 10)");
					//					} else if (month < 9 && dayOfMonth > 10) {
					//						DateInput.setText(year + "-0" + (month + 1)
					//								+ "-" + dayOfMonth);
					//						DLog.i("xiawei", year + "-0" + (month + 1)
					//								+ "-" + dayOfMonth+"(month < 9 && dayOfMonth > 10)");
					//					} else if (month > 9 && dayOfMonth < 10) {
					//						DateInput.setText(year + "-" + (month + 1)
					//								+ "-0" + dayOfMonth);
					//						DLog.i("xiawei", year + "-" + (month + 1)
					//								+ "-0" + dayOfMonth+"(month > 9 && dayOfMonth < 10)");
					//					} else {
					//						DateInput.setText(year + "-" + (month + 1)
					//								+ "-" + dayOfMonth);
					//					}
				}
			}, c.get(Calendar.YEAR), // 传入年份
			c.get(Calendar.MONTH), // 传入月份
			c.get(Calendar.DAY_OF_MONTH) // 传入天数
					);
			break;
		case TIME_DIALOG:
			c = Calendar.getInstance();
			dialog = new TimePickerDialog(this,
					new TimePickerDialog.OnTimeSetListener() {
				@Override
				public void onTimeSet(TimePicker view, int hourOfDay,
						int minute) {
					if (hourOfDay < 10 && minute < 10) {
						TimeInput.setText("0" + hourOfDay + ":0"
								+ minute);
					} else if (hourOfDay < 10 && minute > 10) {
						TimeInput.setText("0" + hourOfDay + ":"
								+ minute);
					} else if (hourOfDay > 10 && minute < 10) {
						TimeInput.setText(+hourOfDay + ":0" + minute);
					} else {
						TimeInput.setText(+hourOfDay + ":" + minute);
					}

				}
			}, c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE),
			false);
			break;
		}
		return dialog;
	}

}
